<?php
    // +----------------------------------------------------------------------
    // | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ] 
    // +----------------------------------------------------------------------
    // | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
    // +----------------------------------------------------------------------
    // | SiteUrl: http://www.luckyhhy.cn
    // +----------------------------------------------------------------------
    // | Author: LuckyHhy <jackhhy520@qq.com>
    // +----------------------------------------------------------------------
    // | Date: 2020/3/12-16:11
    // +----------------------------------------------------------------------
    // | Description:  
    // +----------------------------------------------------------------------


    namespace app\wechat\controller;

    use app\wechat\service\WechatService;
    use think\Db;
    use think\exception\HttpResponseException;

    class Keys extends ChatBase
    {
        /**
         * 绑定数据表
         * @var string
         */
        protected $table = 'WechatKeys';

        /**
         * 消息类型
         * @var array
         */
        public $types = [
            'text'          => '文字',
            'news'          => '图文',
            'image'         => '图片',
            'music'         => '音乐',
            'video'         => '视频',
            'voice'         => '语音',
            'customservice' => '转客服',
        ];

        /**
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: index
         * @describe:回复规则管理
         */
        public function index()
        {
            // 关键字二维码生成
            if ($this->request->get('action') === 'qrc') {
                try {
                    $wechat = WechatService::WeChatQrcode();

                    $result = $wechat->create($this->request->get('keys', ''));

                    $this->success('生成二维码成功！', "javascript:$.previewImage('{$wechat->url($result['ticket'])}')");
                } catch (HttpResponseException $exception) {
                    throw  $exception;
                } catch (\Exception $e) {
                    $this->error("生成二维码失败，请稍候再试！<br> {$e->getMessage()}");
                }
            }
            // 关键字列表显示
            $this->title = '回复规则管理';
            $query       = $this->_query($this->table)->like('keys,type')->equal('status')->dateBetween('create_at');

            $query->whereNotIn('keys', ['subscribe', 'default'])->order('sort desc,id desc')->page();
        }

        /**
         * @param $data
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: _index_page_filter
         * @describe:列表数据处理
         */
        protected function _index_page_filter(&$data)
        {
            foreach ($data as &$vo) {
                $vo['qrc']  = url('@wechat/keys/index')."?action=qrc&keys={$vo['keys']}";
                $vo['type'] = isset($this->types[$vo['type']]) ? $this->types[$vo['type']] : $vo['type'];
            }
        }

        /**
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: add
         * @describe:添加关键字
         */
        public function add()
        {
            $this->applyCsrfToken();
            $this->title = '添加关键字规则';
            $this->_form($this->table, 'form');
        }

        /**
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: edit
         * @describe:编辑关键字
         */
        public function edit()
        {
            $this->applyCsrfToken();
            $this->title = '编辑关键字规则';
            $this->_form($this->table, 'form');
        }



        /**
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: remove
         * @describe:删除关键字
         */
        public function remove()
        {
            $this->applyCsrfToken();
            $this->_delete($this->table);
        }



        /**
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: forbid
         * @describe:禁用关键字
         */
        public function forbid()
        {
            $this->applyCsrfToken();
            $this->_save($this->table, ['status' => '0']);
        }



        /**
         * @throws \think\Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: resume
         * @describe:启用关键字
         */
        public function resume()
        {
            $this->applyCsrfToken();
            $this->_save($this->table, ['status' => '1']);
        }



        /**
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: subscribe
         * @describe:配置关注回复
         */
        public function subscribe()
        {
            $this->applyCsrfToken();
            $this->title = '编辑关注回复规则';
            $this->_form($this->table, 'form', 'keys', [], ['keys' => 'subscribe']);
        }



        /**
         * @throws \think\Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: defaults
         * @describe: 配置默认回复
         */
        public function defaults()
        {
            $this->applyCsrfToken();
            $this->title = '编辑默认回复规则';
            $this->_form($this->table, 'form', 'keys', [], ['keys' => 'default']);
        }



        /**
         * @param array $data
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: _form_filter
         * @describe:添加数据处理
         */
        protected function _form_filter(array &$data)
        {
            if ($this->request->isPost() && isset($data['keys'])) {

                $db = Db::name($this->table)->where('keys', $data['keys']);
                empty($data['id']) || $db->where('id', 'neq', $data['id']);
                if ($db->count() > 0) {
                    $this->error('关键字已经存在，请使用其它关键字！');
                }
            }
            if ($this->request->isGet()) {
                $this->msgTypes     = $this->types;
                $root               = rtrim(dirname(request()->basefile(true)), '\\/');
                $this->defaultImage = "{$root}/static/theme/img/image.png";
            }
        }



        /**
         * @param $result
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/12
         * @name: _form_result
         * @describe:表单结果处理
         */
        protected function _form_result($result)
        {
            if ($result !== false) {
                list($url, $keys) = ['', $this->request->post('keys')];
                if (!in_array($keys, ['subscribe', 'default'])) {
                    $url = url('@admin').'#'.url('wechat/keys/index').'?spm='.$this->request->get('spm');
                }
                $this->success('恭喜, 关键字保存成功!', $url);
            } else {
                $this->error('关键字保存失败, 请稍候再试!');
            }
        }

    }